import { app, BrowserWindow, ipcMain, protocol, net } from 'electron'
import path from 'node:path'
import fs from 'fs/promises'
import started from 'electron-squirrel-startup'
import { createProvider } from './provider/createProvider'
import { lookup } from 'mime-types'
import dotenv from 'dotenv'
dotenv.config({ path: path.join(process.cwd(), '.env') })
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (started) {
  app.quit()
}
const createWindow = async () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1024,
    height: 768,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  ipcMain.handle('copy-image', async (event, imageData) => {
    const { data, name } = imageData
    // 从 base64 提取实际的二进制数据
    const base64Data = data.split(';base64,').pop()

    // 创建目录并保存文件
    const userDataPath = app.getPath('userData')
    const imagesPath = path.join(userDataPath, 'images')
    await fs.mkdir(imagesPath, { recursive: true })

    const newImagePath = path.join(imagesPath, name)
    await fs.writeFile(newImagePath, Buffer.from(base64Data, 'base64'))

    return newImagePath
  })
  ipcMain.on('start-chat', async (event, data) => {
    const { selectModel, messageId, message, providerName } = data
    try {
      const provider = createProvider(providerName)
      const stream = await provider.chat(Array.isArray(message) ? message : [message], selectModel)
      for await (const res of stream) {
        const { is_end, result } = res

        mainWindow.webContents.send('update-message', { messageId, result, is_end })
      }
    } catch (error) {
      mainWindow.webContents.send('update-message', {
        messageId,
        result: error.message || '未知错误',
        is_end: true
      })
    }
  })
  // and load the index.html of the app.
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL)
  } else {
    mainWindow.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`))
  }

  // Open the DevTools.
  mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // 在文件顶部添加导入

  // 修改 app.whenReady() 部分
  app.whenReady().then(() => {
    // 首先注册协议
    protocol.handle('safe-file', async request => {
      try {
        // 正确解析 URL - 先解码 URL 编码的字符
        const urlPath = decodeURIComponent(request.url.replace('safe-file://', ''))

        // 处理 Windows 路径
        let filePath = urlPath
        // 如果路径以单个字母开头且没有冒号，添加冒号
        if (/^[A-Za-z]\//.test(filePath)) {
          filePath = filePath.charAt(0) + ':' + filePath.substring(1)
        }
        // 将正斜杠转换为反斜杠
        filePath = filePath.replace(/\//g, '\\')

        // 检查文件是否存在
        try {
          await fs.access(filePath)
        } catch (err) {
          console.error('文件不存在:', filePath)
          throw new Error(`文件不存在: ${filePath}`)
        }

        // 直接读取文件
        const data = await fs.readFile(filePath)

        // 获取 MIME 类型
        const mimeType = lookup(filePath) || 'application/octet-stream'

        // 返回文件内容
        return new Response(data, {
          headers: {
            'Content-Type': mimeType
          }
        })
      } catch (error) {
        console.error('处理图片请求出错:', error)
        return new Response(`图片加载错误: ${error.message}`, {
          status: 404,
          headers: { 'Content-Type': 'text/plain' }
        })
      }
    })

    // 然后创建窗口
    createWindow()

    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    app.on('activate', () => {
      if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
      }
    })
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
